import { sqlMain } from '@utils/dbconf'
import { usermap } from '@maps/index'
import { success,error,SQL_ERROR } from '@utils/response'
import { analysis } from '@utils/request'
import { encode, decode } from 'js-base64'
import { reginCodeMail,sentMail } from '@utils/mail'
import { toToken,tokenTo,changeToken } from '@utils/tokenOper'
import redisDB from '@utils/redisconf'
const { Random } = require('mockjs')
import fs from 'fs'

export const doLog = async (req,res) =>{
  try{
    const { data } = res.locals
    const { uAccount,uPassword } = data
    let sure
    sure = await sqlMain(usermap.login('account'),[uAccount],true)
    if(!sure) sure = await sqlMain(usermap.login('email'),[uAccount],true)
    if(!sure) return res.send(error(500,'账户不存在'))
    const { ID,PASSWORD,TYPE,EMAIL } = sure
    console.log(`正确密码应该是${PASSWORD}`)
    const token = await toToken({
      id:ID,
      acc:uAccount,
      pass:PASSWORD,
      type:TYPE,
      email:EMAIL
    })//encode(JSON.stringify({ID,PASSWORD}))
    console.log({token})
    return res.send(PASSWORD === uPassword?
      success({
        token
      }):error(500,'密码错误')
    )
  }catch(e){
    console.log(e)
    return res.send(SQL_ERROR)}
}

export const doRegCode = async (req,res) =>{
  try{
    const { data } = res.locals
    const { uEmail } = data
    let { NUM } = await sqlMain(usermap.ishave('email'),[uEmail],true)
    console.log({NUM})
    if(NUM) return res.send(error(500,'该邮箱已使用,请选择找回密码'))
    const account = Random.string('number',Random.integer(6,10))
    if(await sqlMain(usermap.ishave('account'),[account]).NUM)
      return res.send(error(500,'sorry,服务器异常哦'))
    const name = Random.name(true)
    const code = Random.string(7)
    const time = 300
    // await sentMail({to:uEmail,title:'SRC-验证码',text:`您的验证码是${code}，该验证码将于5分钟后失效，请尽快使用。`})
    await reginCodeMail({to:uEmail,code,time}).catch(e=>{
      return res.send(error(time,'发送验证码失败'))
    })
    console.log("\n\n\n\n\n\n\n\n",{code})
    await redisDB.set('0',uEmail,{code,account,name,type:0},300)
    return res.send(success())
  }catch(e){
    console.log(e)
    return res.send(SQL_ERROR)}
}

export const doReg =async (req,res) =>{
  try{
    const { uCode,uEmail,uPassword } = res.locals.data
    const result = await redisDB.get('0',uEmail)
    if(!result) return res.send(error(500,"验证码已过期"))
    const { code,account,name,type } = result
    if(uCode !== code) return res.send(error(500,"验证码错误"))
    await redisDB.del('0',uEmail)//删除
    console.log(`新用户创建了:${account}`)
    await sqlMain(usermap.regin,[account,uPassword,uEmail,type])
    await sqlMain(usermap.regininfo,[name,account])
    return res.send(success({uAccount:account}))
  }catch(e){
    console.log(e)
    return res.send(SQL_ERROR)}
}

export const getInfo = async (req,res) =>{
  try{
    const { data,params } = res.locals
    const { token } = params
    if(!token) return res.send(error(500,'未知的用户'))
    const { id,acc,pass,type,email } = await tokenTo(token)
    console.log({id})
    const info = await sqlMain(usermap.getinfo,[id,acc,pass,type],true)
    const avainfo = await redisDB.get('2',id)
    // info.ava = avainfo? 
    //   `data:${avainfo.filetype};base64,${Buffer.from(fs.readFileSync(avainfo.path), 'binary').toString('base64')}`
    //   :null
    info.acc = acc
    info.type = type
    console.log({email})
    if(email)
      info.email = `${email.slice(0,2)}*****${email.slice(email.length-3)}`
    return res.send(success({info}))
  }catch(e){
    console.log(e)
    return res.send(SQL_ERROR)}
}

export const changeInfo = async (req,res) =>{
  try{
    const { data,token } = res.locals
    if(!token) return res.send(500,'未知的用户')
    const { id } = await tokenTo(token)//acc、pass、type
    const { iid,list } = data
    // console.log(usermap.changeinfo(list),iid,id)
    const tag = await sqlMain(usermap.changeinfo(list),[iid,id])
    console.log("修改成功")
    return res.send(success({tag:true}))
  }catch(e){
    console.log(e)
    return res.send(SQL_ERROR)}
}

